<template>
  <div v-if="flowStore.sectorSchemes && flowStore.sectorSchemes.length > 0">
    <div
      style="
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding-bottom: 12px;
      "
    >
      <div>
        <el-button
          :type="
            flowStore.selectedSectorScheme.number == -1 ? 'success' : 'warning'
          "
          size="small"
          link
        >
          <el-icon v-if="flowStore.selectedSectorScheme.number == -1"
            ><SuccessFilled
          /></el-icon>
          <el-icon v-else><WarningFilled /></el-icon>
          <span style="padding-right: 3px">扇区参数:</span>
          <b>{{ flowStore.selectedSectorScheme.title }}</b>
          <!-- <b v-if="flowStore.selectedSectorScheme.number != -1">(非当前)</b> -->
        </el-button>
      </div>
      <div>
        <el-button type="info" size="small" link @click="handleRefresh()">
          <el-icon><Refresh /></el-icon>
          <!-- <span>刷新列表</span> -->
        </el-button>
      </div>
    </div>
    <div
      style="
        display: flex;
        justify-content: space-between;
        padding: 12px 24px 12px 6px;
      "
    >
      <el-button type="primary" size="small" @click="handleEditorCreate()">
        <el-icon><Plus /></el-icon>
        <span>新建自定义预设</span>
      </el-button>
      <el-dropdown trigger="click" @command="handleFilter">
        <el-button type="primary" size="small" link>
          <span>过滤：</span>
          <span>{{
            sectorCountingLimit == 0 ? "全部" : sectorCountingLimit + "扇区"
          }}</span>
          <el-icon class="el-icon--right">
            <arrowDown />
          </el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item :command="0">全部</el-dropdown-item>
            <el-dropdown-item :command="1">1扇区</el-dropdown-item>
            <el-dropdown-item :command="2">2扇区</el-dropdown-item>
            <el-dropdown-item :command="3">3扇区</el-dropdown-item>
            <el-dropdown-item :command="4">4扇区</el-dropdown-item>
            <el-dropdown-item :command="5">5扇区</el-dropdown-item>
            <el-dropdown-item :command="6">6扇区</el-dropdown-item>
            <el-dropdown-item :command="7">7扇区</el-dropdown-item>
            <el-dropdown-item :command="8">8扇区</el-dropdown-item>
            <el-dropdown-item :command="9">9扇区</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <el-scrollbar :height="paneHeight">
      <div v-for="(item, index) in flowStore.sectorSchemes">
        <div
          v-if="
            sectorCountingLimit == 0 ||
            countSeat(item.content) == sectorCountingLimit ||
            item.type == '当前'
          "
          class="scheme-wrapper"
        >
          <div>
            <span style="font-size: 14px; font-weight: bold">{{
              item.title
            }}</span>
            <el-tag
              style="margin-left: 6px"
              :type="
                item.type == '当前'
                  ? 'success'
                  : item.type == '预设'
                  ? ''
                  : 'info'
              "
              size="small"
              >{{ item.type }}</el-tag
            >
            <el-tag
              v-if="item.number == null"
              style="margin-left: 6px"
              size="small"
              type="warning"
              >未保存</el-tag
            >
            <el-tag
              v-if="item.number == flowStore.selectedSectorScheme.number"
              style="margin-left: 6px"
              size="small"
              type="success"
              >使用中</el-tag
            >
          </div>
          <div>
            <span style="font-weight: bold; padding-right: 6px">说明:</span>
            <span>{{ item.description }}</span>
          </div>
          <div>
            <span style="font-weight: bold; padding-right: 6px">扇区数量:</span>
            <span>{{ countSeat(item.content) }}</span>
          </div>
          <div>
            <span style="font-weight: bold; padding-right: 6px">适用于:</span>
            <span
              :style="{
                color: detectDirection(item.content).includes('南')
                  ? '#F56C6C'
                  : '#409EFF',
              }"
              >{{ detectDirection(item.content) }}</span
            >
          </div>
          <div class="scheme-content-seat">
            <div v-for="seat in item.content">
              <div v-if="seat.sectorCodes.length > 0">
                <span style="font-weight: bold; padding-right: 6px"
                  >{{ seat.seatName }}:</span
                >
                <span style="opacity: 0.85">{{
                  seat.sectorCodes.join(" ")
                }}</span>
                <!-- <el-tag size="small" v-for="code in seat.sectorCodes">{{
                code
              }}</el-tag> -->
              </div>
            </div>
          </div>
          <div class="scheme-content-operator">
            <el-button
              type="primary"
              size="small"
              @click="handleSelect(item.number)"
              :disabled="
                item.number == null ||
                item.number == flowStore.selectedSectorScheme.number
              "
            >
              <el-icon><DArrowLeft /></el-icon>
              <span>使用</span>
            </el-button>
            <div>
              <el-button
                type="primary"
                size="small"
                text
                @click="handleEditorOpen(index - 1)"
                :disabled="item.type != '自定义' || editorIndex == index - 1"
              >
                <el-icon><Edit /></el-icon>
                <span>编辑</span>
              </el-button>
              <el-button
                type="danger"
                size="small"
                text
                :disabled="item.type != '自定义'"
                @click="handleDelete(index - 1)"
              >
                <el-icon><Delete /></el-icon>
                <span>删除</span>
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <!-- <pre>{{ flowStore.presetSectorSchemes }}</pre> -->
    </el-scrollbar>

    <el-dialog
      v-model="showEditor"
      title="编辑扇区模板"
      width="800px"
      draggable
      destroy-on-close
      append-to-body
      :show-close="false"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <div v-if="showEditor && editorIndex != -1 && editorContent != null">
        <el-form inline size="small">
          <el-form-item label="标题">
            <el-input
              v-model="editorContent.title"
              :disabled="editorContent.type != '自定义'"
            ></el-input>
          </el-form-item>
          <el-form-item label="类型">
            <el-input v-model="editorContent.type" disabled></el-input>
          </el-form-item>
          <el-form-item label="说明" style="width: 100%">
            <el-input
              v-model="editorContent.description"
              :disabled="editorContent.type != '自定义'"
              style="width: 100%"
            ></el-input>
          </el-form-item>
        </el-form>
        <!-- draggable -->
        <div style="display: flex; flex-flow: wrap">
          <div
            class="planner-wrapper-seat"
            v-for="seat in editorContent.content"
            :style="{
              width:
                seat.sectorCodes.length < 5
                  ? 'calc(25% - 8px)'
                  : seat.sectorCodes.length < 10
                  ? 'calc(50% - 8px)'
                  : seat.sectorCodes.length < 15
                  ? 'calc(75% - 8px)'
                  : '100%',
            }"
          >
            <div class="planner-wrapper-seat-title">
              <span>{{ seat.seatName }}</span>
              <span
                :style="{
                  backgroundColor: commonStore.darkMode
                    ? flowStore.seatColors[seat.seatName][0]
                    : flowStore.seatColors[seat.seatName][1],
                  width: '24px',
                  height: '12px',
                  borderRadius: '3px',
                }"
              ></span>
            </div>
            <draggable
              class="planner-wrapper-seat-content"
              v-model="seat.sectorCodes"
              group="sector"
              :disabled="editorContent.type != '自定义'"
              :sort="true"
              :animation="500"
              @start="drag = true"
              @end="drag = false"
              item-key="id"
            >
              <template #item="{ element }">
                <el-tag class="planner-sector-code">{{ element }}</el-tag>
              </template>
            </draggable>
          </div>
        </div>
        <div class="planner-wrapper-command">
          <el-button
            type="primary"
            size="small"
            @click="handleEditorSave()"
            :disabled="!editorChanged"
          >
            <el-icon><UploadFilled /></el-icon>
            <span>保存</span>
          </el-button>
          <el-button
            type="warning"
            size="small"
            text
            @click="handleEditorRestore()"
            :disabled="!editorChanged"
          >
            <el-icon><Refresh /></el-icon>
            <span>复原</span>
          </el-button>
          <el-button
            type="danger"
            size="small"
            text
            @click="handleEditorCancel()"
          >
            <el-icon><Close /></el-icon>
            <span>取消</span>
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, onMounted, onUnmounted } from "vue";
import useFlowStore from "@/store/flow.js";
import useCommonStore from "@/store/common.js";
import dateFormat from "@/utils/dateFormat.js";
import draggable from "vuedraggable";
import { ElNotification, ElMessageBox } from "element-plus";

const flowStore = useFlowStore();
const commonStore = useCommonStore();

// initialize sector schemes list
let refreshTimer = null;
onMounted(() => {
  flowStore.loadPresetSectorSchemes();
  refreshTimer = setInterval(() => {
    if (editorIndex == -1) {
      flowStore.loadPresetSectorSchemes();
    }
  }, 10000);
});
onUnmounted(() => {
  clearInterval(refreshTimer);
  refreshTimer = null;
});

const handleSelect = (number) => {
  flowStore.selectedSchemeNumber = number;
};

const handleRefresh = () => {
  if (editorIndex.value == -1) {
    flowStore.loadPresetSectorSchemes().then(() => {
      ElNotification({ title: "列表已刷新", type: "success" });
    });
  } else {
    ElMessageBox.confirm(
      "刷新列表会导致编辑中的未保存数据将会消失。请返回编辑页面，点击保存，列表会自动刷新",
      "编辑器中存在数据",
      {
        confirmButtonText: "好",
        cancelButtonText: "放弃数据并刷新",
        type: "warning",
      }
    )
      .then()
      .catch(() => {
        flowStore.loadPresetSectorSchemes().then(() => {
          ElNotification({ title: "列表已刷新", type: "success" });
        });
      });
  }
};

// data and ui selectors
const editorIndex = ref(-1);
const showEditor = ref(false);
const editorBackup = ref("");
const editorContent = ref(null);
const editorChanged = computed(() =>
  showEditor.value
    ? editorBackup.value != JSON.stringify(editorContent.value)
    : false
);

const handleEditorCreate = () => {
  // flowStore.currentSectorScheme
  let newScheme = JSON.parse(JSON.stringify(flowStore.sectorSchemes[0]));
  newScheme.number = null;
  newScheme.title = "新建自定义预设";
  newScheme.description = "新建的自定义扇区预设 @" + dateFormat();
  newScheme.type = "自定义";
  // flowStore.presetSectorSchemes.push(newScheme);
  editorBackup.value = JSON.stringify(newScheme);
  editorContent.value = JSON.parse(editorBackup.value);
  setTimeout(() => {
    editorIndex.value = flowStore.presetSectorSchemes.length - 1;
    showEditor.value = true;
  }, 100);
};

const handleEditorOpen = (index) => {
  editorBackup.value = JSON.stringify(flowStore.presetSectorSchemes[index]);
  editorContent.value = JSON.parse(editorBackup.value);
  setTimeout(() => {
    editorIndex.value = index;
    showEditor.value = true;
  }, 100);
};

const handleEditorSave = async () => {
  await nextTick();
  flowStore.saveSectorScheme(editorContent.value).then((result) => {
    ElNotification({
      title: result ? "已保存" : "保存失败！",
      type: result ? "success" : "danger",
    });
    showEditor.value = false;
    editorIndex.value = -1;
    setTimeout(() => {
      editorContent.value = null;
      editorBackup.value = "";
    }, 100);
  });
};

const handleEditorRestore = () => {
  editorContent.value = JSON.parse(editorBackup.value);
};

const handleEditorCancel = () => {
  showEditor.value = false;
  editorIndex.value = -1;
  setTimeout(() => {
    editorContent.value = null;
    editorBackup.value = "";
  }, 100);
};

const handleDelete = (index) => {
  ElMessageBox.confirm(
    `确认要删除“${flowStore.presetSectorSchemes[index].title}”吗？`,
    "删除",
    {
      confirmButtonText: "删除",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(() => {
    let number = flowStore.presetSectorSchemes[index].number;
    if (number == null) {
      flowStore.presetSectorSchemes.splice(index, 1);
      ElNotification({ title: "已删除", type: "success" });
    } else {
      flowStore.deleteSectorScheme(number).then((result) => {
        ElNotification({
          title: result ? "已删除" : "删除失败！",
          type: result ? "success" : "danger",
        });
      });
    }
  });
};

const countSeat = (content) => {
  let count = 0;
  content.forEach((seat) => {
    if (seat.sectorCodes.length > 0) {
      count++;
    }
  });
  return count;
};

const detectDirection = (content) => {
  let direction = { ZUUU: "向北", ZUTF: "向北" };
  content.forEach((seat) => {
    if (
      seat.sectorCodes.includes("AP18") &&
      seat.sectorCodes.includes("AP81")
    ) {
      direction.ZUUU = "任意";
    } else if (
      seat.sectorCodes.includes("AP01") &&
      seat.sectorCodes.includes("AP81")
    ) {
      direction.ZUUU = "向南";
    }
    if (
      seat.sectorCodes.includes("APC7") &&
      seat.sectorCodes.includes("AP7C")
    ) {
      direction.ZUTF = "任意";
    } else if (
      seat.sectorCodes.includes("AP12") &&
      seat.sectorCodes.includes("AP7C")
    ) {
      direction.ZUTF = "向南";
    }
  });
  return `双流${direction.ZUUU} / 天府${direction.ZUTF}`;
};

const sectorCountingLimit = ref(0);
const handleFilter = (count) => {
  sectorCountingLimit.value = count;
};

const paneHeight = computed(() => {
  let width =
    commonStore.clientWidth -
    commonStore.showSidebar * commonStore.sidebarWidth -
    424;
  // let height = Math.max(640, Math.round((width / 1008.51) * 775.86)) - 60;
  let height = Math.max(640, Math.round((width / 822) * 630)) - 36;
  return height + "px";
});
</script>

<style scoped>
* {
  box-sizing: border-box;
}

.scheme-wrapper {
  margin: 12px 6px;
  padding: 12px;
  /* cursor: pointer; */
  user-select: none;
  font-size: 12px;
  border: 1px solid rgba(128, 128, 128, 0.3);
  border-radius: 6px;
  opacity: 0.8;
  transform: scale(1);
  transition: all 0.2s ease-out;
}
.scheme-wrapper > * {
  margin: 6px;
}

.scheme-wrapper:hover {
  background-color: rgba(128, 128, 128, 0.1);
  /* transform: scale(1.02); */
  opacity: 1;
}

.planner-wrapper-seat {
  font-size: 12px;
  height: 100%;
  overflow: auto;
  margin: 4px;
  background-color: rgba(255, 255, 255, 0.02);
  border: 1px solid rgba(128, 128, 128, 0.2);
  border-radius: 4px;
  transition: all 0.5s ease-in-out;
}

.planner-wrapper-seat:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
}

.planner-wrapper-seat-title {
  width: 100%;
  padding: 3px 6px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: rgba(255, 255, 255, 0.03);
  border-bottom: 1px solid rgba(128, 128, 128, 0.2);
}

.planner-wrapper-seat-content {
  width: 100%;
  min-height: 36px;
  padding: 4px;
  text-align: justify;
  /* border: 1px solid #f66; */
}

.planner-sector-code {
  margin: 2px;
  font-size: 12px;
  user-select: none;
  cursor: pointer;
  font-family: "Consolas";
  height: 18px;
  width: 36px;
}

.planner-wrapper-command {
  margin-top: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.planner-wrapper-command > * {
  margin: 0 12px;
  /* min-width: 64px; */
}

.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}

.scheme-content-operator {
  padding: 6px 3px 0 3px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.scheme-content-seat {
  border-top: 1px solid rgba(128, 128, 128, 0.5);
  border-bottom: 1px solid rgba(128, 128, 128, 0.5);
  font-family: "Consolas";
  padding: 6px 0;
}
</style>
